package top.ffhome.blog.service.impl;

import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import top.ffhome.blog.entity.Label;
import top.ffhome.blog.mapper.LabelMapper;
import top.ffhome.blog.service.LabelService;
import top.ffhome.common.audit.AuditOperation;
import top.ffhome.common.audit.AuditService;
import top.ffhome.common.service.impl.BaseServiceImpl;
import top.ffhome.util.core.TreeUtil;

@Service
@AuditService(entity = Label.class)
public class LabelServiceImpl extends BaseServiceImpl<Label, LabelMapper> implements LabelService {
	@Override
	@CacheEvict(value = { "label_getTree", "label_selectLabelsByCreateBy" }, allEntries = true)
	public void clearCache() {
	}

	@Override
	@Cacheable("label_getTree")
	public List<Label> getTree() {
		Label dto = new Label();
		dto.getParams().put("orderBy", "sort");
		List<Label> list = mapper.select(dto);
		return TreeUtil.generate(list, new Label());
	}

	@Override
	@Cacheable("label_selectLabelsByCreateBy")
	public List<Label> selectLabelsByCreateBy(Long createBy) {
		return mapper.selectLabelsByCreateBy(createBy);
	}

	@Override
	@AuditOperation(type = AuditOperation.UPDATE)
	public void move(Label label) {
		if (label.getSort() == 0) {
			Integer max = mapper.getMaxSortByParentId(label.getParentId());
			if (max == null) {
				max = 0;
			}
			label.setSort(max + 1);
		} else {
			mapper.moveNextSiblingsSort(label.getParentId(), label.getSort());
		}
		mapper.update(label);
		getSelf().clearCache();
	}

	@Override
	protected void beforeInsert(Label label) {
		if (label.getSort() == null || label.getSort() == 0) {
			Integer max = mapper.getMaxSortByParentId(label.getParentId());
			if (max == null) {
				max = 0;
			}
			label.setSort(max + 1);
		}
		super.beforeInsert(label);
	}
}
